<template>
  <view class="main" :style="{ backgroundImage: `url(${bgImage})` }">
    <view class="contentNew">
      <!-- 帮助部分 -->
      <view class="help-view">
        <image class="help-button" :src="helpBtnImage" mode="heightFix" />
      </view>
      <!-- 内容部分 -->
      <view class="content-view"></view>

      <!-- <button class="login"  @click="fjgl" v-if="usertype=='12'">房间管理</button> -->
      <view class="money-view" v-if="isShow">
        <text class="num-text">预约时间</text>
        <text class="num-text-mini">开始时间：{{ startTime }}</text>
        <text class="num-text-mini">结束时间：{{ endTime }}</text>
        <!--          <text class="num-text-mini">天</text>
          <text class="num-text">{{ hourNum }}</text>
          <text class="num-text-mini">小时</text> -->
      </view>

      <!-- 底部按钮 -->
      <view class="button-view" v-if="isLogin">
        <!-- <image @click="clickStartUseBtn" class="now-book-button" :src="startUserBtnImage" mode="widthFix" /> -->
        <view class="loginView" @click="clickStartUseBtn">
            <view class="loginViewTitle">
              预约订单查询
            </view>
            <view class="loginViewDesc">
              （手机号仅用于查询预约订单）
            </view>
        </view>
      </view>
      <view class="button-view" v-else>
<!--        <button class="now-book-button" @click="tologin">
          <image class="now-book-image" :src="startUserBtnImage" mode="widthFix" />
        </button> -->

        <view class="loginView"  @click="tologin">
            <view class="loginViewTitle">
              预约订单查询
            </view>
            <view class="loginViewDesc">
              （手机号仅用于查询预约订单）
            </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    onMounted,
    reactive,
    ref
  } from 'vue'
  import button_add from '@/static/images/button_add.png'
  import {
    base64_index_bg_image
  } from '@/static/base64'
  import button_start_use from '@/static/images/button_start_use.png'
  // 在页面中导入相关 api
  import {
    getRoomInfo,
    weixinMinAppLogin,
    userget
  } from '@/api/index'
  import {
    onLoad
  } from '@dcloudio/uni-app'

  const bgImage = base64_index_bg_image // 背景图片
  const helpBtnImage = ref(button_add) // 帮助按钮图片
  const startUserBtnImage = ref(button_start_use) // 开始使用按钮图片

  const storeId = ref('')
  const roomId = ref('')
  const startTime = ref('2025-05-05 10:30:00')
  const endTime = ref('2025-05-05 11:30:00')
  const price = ref(0)
  const timeselectindex = ref(0)
  const select_time_index = ref(0)
  const roominfodata = reactive({})
  const payselectindex = ref(1)
  const pricestring = ref(0)
  const hour_options = ref([])
  const nightLong = ref(false)
  const isLogin = ref(false)
  const orderNo = ref('')
  const submit_begin_time = ref('')
  const submit_end_time = ref('')

  const isShow = ref(false)

  const fjgl = () => {

  }

  // 点击 - 开始使用按钮
  const clickStartUseBtn = () => {


    if (uni.getStorageSync("startDate") == "" || uni.getStorageSync("endDate") == "") {


      getUserOrder(wx.getStorageSync('token').userId)
      getUserDesc(wx.getStorageSync('token').userId)
    }

    console.log('点击了开始使用按钮')
    checkTimeRange(uni.getStorageSync("startDate"), uni.getStorageSync("endDate"))
  }

  // 检查当前时间与日期区间的关系
  const checkTimeRange1 = (startDateStr, endDateStr) => {

    if (uni.getStorageSync("startDate") == "" || uni.getStorageSync("endDate") == "") {
      isShow.value = false
      return;
    }

    // 1. 转换为 Date 对象
    const startDate = parseCustomDate(startDateStr);
    const endDate = parseCustomDate(endDateStr);
    const now = new Date();

    // 2. 验证日期有效性
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {

      isShow.value = false
    }

    // 3. 检查时间关系
    if (now < startDate) {

      isShow.value = true
      return 'active'; // 在预约时间内
    } else {

      isShow.value = false
      return 'expired'; // 已过结束时间
    }
  }

  // 检查当前时间与日期区间的关系
  const checkTimeRange = (startDateStr, endDateStr) => {
    // 1. 转换为 Date 对象
    const startDate = parseCustomDate(startDateStr);
    const endDate = parseCustomDate(endDateStr);
    const now = new Date();

    // 2. 验证日期有效性
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      throw new Error('无效的日期格式');
    }

    // 3. 检查时间关系
    if (now < startDate) {
      uni.showToast({
        title: '未到预约时间，预约时间为:' + uni.getStorageSync("startDate"),
        icon: 'none',
      })
      return 'before'; // 未到预约时间
    } else if (now >= startDate && now <= endDate) {

          uni.navigateTo({
            url: '/pages/reserve/contentNew',
          })




      return 'active'; // 在预约时间内
    } else {
      uni.removeStorageSync("startDate")
      uni.removeStorageSync("endDate")


      getUserDesc(wx.getStorageSync('token').userId)

      getUserOrder(wx.getStorageSync('token').userId)
      return 'expired'; // 已过结束时间
    }
  }

  const parseCustomDate = (dateStr) => {
    // 将 "2025/04/22 20:00" 转换为 Date 对象
    const [datePart, timePart] = dateStr.split(' ');
    const [year, month, day] = datePart.split('-');
    const [hours, minutes,second] = timePart.split(':');

    // 注意：月份是 0-11，所以要减1
    return new Date(year, month - 1, day, hours, minutes);
  }

  const getUserDesc = (id) => {
    if (!id) return;

    uni.request({
      url: 'https://sharebilliardstcp.wteam.club/macback/getUserInfo?id=' + id,
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },

      success(res) {
        console.log('用户信息', res)

        uni.setStorageSync("petInfo",res.data.data)

        // if (!res.data.data.pet_nickname) {

        //   uni.navigateTo({
        //     url: '/pages/reserve/contentNew',
        //   })
        // } else {


        // }

      },
    })

  }

  const tologin = ()=>{

    uni.navigateTo({
      url: '/pages/login/login',
    })

  }



  const getUserOrder = (id) => {

    if (!id) return;

    uni.request({
      url: 'https://sharebilliardstcp.wteam.club/macback/getUserOrder?id=' + id,
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },

      success(res) {
        console.log('用户订单', res)
        if(res.data.data.length >0){

           uni.setStorageSync("startDate",res.data.data[0].start_time)
           uni.setStorageSync("endDate",res.data.data[0].end_time)

          let storeId1 = res.data.data[0].store_id
          let roomId1 = res.data.data[0].room_id
          storeId.value = storeId1
          roomId.value = roomId1
          wx.setStorageSync('global_store_id', storeId1)
          wx.setStorageSync('global_room_id', roomId1)


           startTime.value = res.data.data[0].start_time
           endTime.value = res.data.data[0].end_time

           isShow.value = true
        }else{

          isShow.value = false

          uni.showToast({
            title: '尚未预约，请联系店主预约',
            icon: 'none',
          })
        }


      },
    })

  }


  // 定义存储请求的结果
  const studyList = ref([])

  // 也买你加载完毕执行
  onMounted(() => {
    // 调用函数
    // getStudyList();
  })

  onLoad((option) => {
    // 调用函数
    var storeId1 = '17'
    var roomId1 = '25'
    var timeselectindex1 = 0
    var goPage = 1
    // const storeName = options.storeName;
    if (uni.getStorageSync('token')) isLogin.value = true
    else isLogin.value = false

    if (goPage) {
      //点按钮跳转的
    } else {
      var query = wx.getEnterOptionsSync().query
      console.log(query)
      if (query) {
        if (query.storeId) {
          storeId1 = query.storeId
        }
        if (query.roomId) {
          roomId1 = query.roomId
        }
        if (query.timeselectindex) {
          timeselectindex1 = query.timeselectindex
        }
      }
    }

    storeId.value = storeId1
    roomId.value = roomId1
    timeselectindex.value = timeselectindex1
    const startDate = new Date()
    submit_begin_time.value = formatDate(startDate).text

    // that.daySlotInit();
    wx.setStorageSync('global_store_id', storeId1)
    wx.setStorageSync('global_room_id', roomId1)

    getRoomInfoIndex(roomId1)

    getuserinfo();

    // checkTimeRange1();

    getUserOrder(wx.getStorageSync('token').userId)
    getUserDesc(wx.getStorageSync('token').userId)

  })

  // 封装函数，调用 api
  const getRoomInfoIndex = async (roomId) => {
    let res = await getRoomInfo(roomId)
    console.log(res)
  }

  const formatDate = (dateTime) => {
    const date = new Date(dateTime)
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let hour = date.getHours()
    let minute = date.getMinutes()
    if (minute < 10) {
      minute = `0${minute}`
    }
    if (hour < 10) {
      hour = `0${hour}`
    }
    if (day < 10) {
      day = `0${day}`
    }
    if (month < 10) {
      month = `0${month}`
    }
    return {
      text: `${year}/${month}/${day} ${hour}:${minute}`,
      year,
      month,
      day,
      hour,
      minute,
    }
  }
  const usertype = ref("11");

  const getuserinfo = async () => {
    var that = this;
    if (uni.getStorageSync("token")) {
      let info = await userget()

      console.log("111", info);
      usertype.value = info.data.userType
    }
  }


//   const getPhoneNumber = (e) => {
//     console.log('授权用户手机号')
//     var that = this
//     if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
//       wx.showToast({
//         title: '已取消授权',
//       })
//     }
//     if (e.detail.errMsg == 'getPhoneNumber:ok') {
//       wx.login({
//         success: async (res) => {
//           if (res.code != null) {
//             let info = await weixinMinAppLogin({
//               phoneCode: e.detail.code,
//               loginCode: res.code,
//             })
//             console.log(info)

//             if (info.code == 0) {
//               if (info.data) {
//                 isLogin.value = true

//                 getuserinfo();

//                 //缓存服务器返回的用户信息
//                 wx.setStorageSync('token', info.data)
//                 wx.showToast({
//                   title: '登录成功',
//                   icon: 'none',
//                 })
//                 setTimeout(function() {

//                   getUserDesc(info.data.userId)
//                   getUserOrder(info.data.userId)

//                 }, 2000)

//               }
//             }
//           } else {
//             console.log('登录失败！' + res.errMsg)
//           }
//         },
//       })
//     } else {
//       console.log(e.detail.errMsg)
//     }
//   }
</script>

<style scoped lang="scss">
  .loginView {
    background: #f2f2f2;
        color: #274a83;
        width: 80%;
        border-radius: 8px;
        text-align: center;
        font-size: 18px;
        font-weight: 600;
        padding: 10px;

        .loginViewDesc {

    font-size: 15px;
        }
  }



  // 金额 元素居中
  .money-view {
    // margin-top: 3%;
    height: 10%;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
    margin-bottom:20px;

    .sign-text {
      font-size: 30rpx;
      color: white;
    }

    .num-text {
      font-size: 70rpx;
      color: white;
      // 向上偏移
      margin-top: -6%;
    }

    .num-text-mini {
      font-size: 32rpx;
      color: white;
      margin-bottom: 5px;
    }
  }

  .login {
    /* background: #32CD32; */
    /* background: #FF7F00; */
    width: 80%;
    height: 78rpx;

    color: rgba(255, 255, 255, 1);
    background-color: rgba(73, 194, 101, 1);
    border-radius: 6rpx;
    font-size: 28rpx;
    line-height: 150%;
    text-align: center;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
  }


  .main {
    display: flex;
    flex-direction: column;
    height: 100vh;
    // 背景图片自适应
    background-size: 100% 100%;

    .contentNew {
      flex: 1;
      overflow: auto;
      padding: 40rpx 20rpx;

      // 帮助部分
      .help-view {
        height: 8%;
        padding: 3%;

        .help-button {
          height: 42rpx;
          float: right;
        }
      }

      // 内容部分
      .content-view {
        height: 50%;
      }

      // 底部按钮
      .button-view {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 22%;

        .now-book-button {
          width: 80%;
        }

        .now-book-image {
          width: 100%;
        }
      }
    }
  }
</style>
